﻿using System;
using System.Collections.Generic;
using System.Text;

namespace Framework.Message.SMS.SGIP
{
    public class CommandSequence
    {
        #region 变量与属性
        private uint _SrcID = 0;
        /// <summary>
        /// 命令源节点的编号
        /// </summary>
        public uint SrcID
        {
            get { return _SrcID; }
            set { _SrcID = value; }
        }

        private uint _DateSequence = 0;
        /// <summary>
        /// 命令产生的日期和时间(网关系统中的任何命令的保存时间都不应该超过一年)，格式为十进制的mmddhhmmss，比如11月20日20时32分25秒产生的命令，其第二部分为十进制1120203225
        /// </summary>
        public uint DateSequence
        {
            get { return _DateSequence; }
            set { _DateSequence = value; }
        }

        private uint _MsgSequence = 0;
        /// <summary>
        /// 由0开始，循环进位，直到进位满了之后再清零，重新开始计数。接收方在返回应答时，应答的序列号必须和相对应的命令的序列号相同。
        /// </summary>
        public uint MsgSequence
        {
            get { return _MsgSequence; }
            set { _MsgSequence = value; }
        }
        #endregion

        #region 构造函数
        public CommandSequence()
        {

        }

        public CommandSequence(string srcNoteNum, DateTime date, uint msgSeq)
        {
            _SrcID = uint.Parse(srcNoteNum);
            _DateSequence = uint.Parse(date.ToString("MMddHHmmss"));
            _MsgSequence = msgSeq;
        }
        public CommandSequence(byte[] bytes)
        {
            ByteTo(bytes, 0);
        }

        public CommandSequence(byte[] bytes, int startIndex)
        {
            ByteTo(bytes, startIndex);
        }
        #endregion

        private void ByteTo(byte[] bytes, int startIndex)
        {
            int i = startIndex;
            this._SrcID = ByteIntConvert.Bytes2UInt(bytes, i);
            i += 4;
            this._DateSequence = ByteIntConvert.Bytes2UInt(bytes, i);
            i += 4;
            this._MsgSequence = ByteIntConvert.Bytes2UInt(bytes, i);
        }

        public byte[] ToByte()
        {
            //消息长度
            byte[] bytes = new byte[4 + 4 + 4];
            byte[] t = ByteIntConvert.UInt2Bytes(SrcID);
            for (int i = 0; i < 4; i++)
            {
                bytes[i] = t[i];
            }

            t = ByteIntConvert.UInt2Bytes(DateSequence);
            for (int i = 0; i < 4; i++)
            {
                bytes[i + 4] = t[i];
            }

            t = ByteIntConvert.UInt2Bytes(MsgSequence);
            for (int i = 0; i < 4; i++)
            {
                bytes[i + 4 + 4] = t[i];
            }
            return bytes;
        }

        public override string ToString()
        {
            return this._SrcID.ToString().PadLeft(4, '0') 
                + _DateSequence.ToString().PadLeft(10, '0')
                + _MsgSequence.ToString().PadLeft(4, '0');
        }
    }
}
